package com.example.service.impl;

import com.example.entity.FinancialIndicator;
import com.example.repository.FinancialIndicatorRepository;
import com.example.service.FinancialIndicatorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 财务指标Service实现类
 */
@Slf4j
@Service
public class FinancialIndicatorServiceImpl implements FinancialIndicatorService {

    @Autowired
    private FinancialIndicatorRepository financialIndicatorRepository;

    @Override
    public double calculateDTI(Long userId) {
        // 获取用户最新的财务指标数据
        Optional<FinancialIndicator> indicatorOpt = financialIndicatorRepository.findLatestByUserId(userId);

        if (indicatorOpt.isEmpty()) {
            log.warn("用户[{}]没有财务指标数据", userId);
            return 0.0;
        }

        FinancialIndicator indicator = indicatorOpt.get();

        // 计算负债收入比 = 负债总额 / 月收入
        if (indicator.getMonthlyIncome() == null || indicator.getMonthlyIncome().compareTo(BigDecimal.ZERO) <= 0) {
            log.warn("用户[{}]月收入为零或负值", userId);
            return 0.0;
        }

        BigDecimal debtAmount = indicator.getDebtAmount() == null ? BigDecimal.ZERO : indicator.getDebtAmount();
        BigDecimal dti = debtAmount.divide(indicator.getMonthlyIncome(), 4, RoundingMode.HALF_UP);

        // 更新DTI值
        indicator.setDebtToIncomeRatio(dti);
        financialIndicatorRepository.save(indicator);

        return dti.doubleValue();
    }

    @Override
    public double calculateDisposableIncome(Long userId) {
        // 获取用户最新的财务指标数据
        Optional<FinancialIndicator> indicatorOpt = financialIndicatorRepository.findLatestByUserId(userId);

        if (indicatorOpt.isEmpty()) {
            log.warn("用户[{}]没有财务指标数据", userId);
            return 0.0;
        }

        FinancialIndicator indicator = indicatorOpt.get();

        // 计算可支配收入 = 月收入 - 负债总额
        BigDecimal monthlyIncome = indicator.getMonthlyIncome() == null ? BigDecimal.ZERO : indicator.getMonthlyIncome();
        BigDecimal debtAmount = indicator.getDebtAmount() == null ? BigDecimal.ZERO : indicator.getDebtAmount();
        BigDecimal disposableIncome = monthlyIncome.subtract(debtAmount);

        // 更新可支配收入
        indicator.setDisposableIncome(disposableIncome);
        financialIndicatorRepository.save(indicator);

        return disposableIncome.doubleValue();
    }

    @Override
    public double calculateIncomeVolatility(Long userId) {
        // 模拟获取用户近6个月的收入数据
        // 实际项目中应从银行流水表或其他数据源获取
        List<BigDecimal> monthlyIncomes = getRecentSixMonthIncomes(userId);

        if (monthlyIncomes.isEmpty()) {
            log.warn("用户[{}]没有近6个月收入数据", userId);
            return 0.0;
        }

        // 计算平均收入
        BigDecimal sum = BigDecimal.ZERO;
        for (BigDecimal income : monthlyIncomes) {
            sum = sum.add(income);
        }
        BigDecimal avgIncome = sum.divide(new BigDecimal(monthlyIncomes.size()), 2, RoundingMode.HALF_UP);

        // 计算方差
        BigDecimal variance = BigDecimal.ZERO;
        for (BigDecimal income : monthlyIncomes) {
            BigDecimal diff = income.subtract(avgIncome);
            variance = variance.add(diff.multiply(diff));
        }
        variance = variance.divide(new BigDecimal(monthlyIncomes.size()), 2, RoundingMode.HALF_UP);

        // 计算标准差
        BigDecimal stdDev = new BigDecimal(Math.sqrt(variance.doubleValue()));

        // 计算变异系数（波动率）= 标准差 / 平均值
        BigDecimal volatility = stdDev.divide(avgIncome, 4, RoundingMode.HALF_UP);

        // 获取用户最新的财务指标数据并更新
        Optional<FinancialIndicator> indicatorOpt = financialIndicatorRepository.findLatestByUserId(userId);

        if (indicatorOpt.isPresent()) {
            FinancialIndicator indicator = indicatorOpt.get();
            indicator.setSixMonthAvgIncome(avgIncome);
            indicator.setIncomeVolatility(volatility);
            financialIndicatorRepository.save(indicator);
        }

        return volatility.doubleValue();
    }

    /**
     * 模拟获取用户近6个月的收入数据
     * 实际项目中应从银行流水表或其他数据源获取
     */
    private List<BigDecimal> getRecentSixMonthIncomes(Long userId) {
        // 模拟数据，实际项目中应从数据库获取
        List<BigDecimal> incomes = new ArrayList<>();
        // 假设用户有6个月的收入记录
        incomes.add(new BigDecimal("8000"));
        incomes.add(new BigDecimal("8200"));
        incomes.add(new BigDecimal("7800"));
        incomes.add(new BigDecimal("8500"));
        incomes.add(new BigDecimal("8300"));
        incomes.add(new BigDecimal("8100"));
        return incomes;
    }
}